﻿using System;
using housingsafety.server.Helpers;
using housingsafety.server.Security;
using housingsafety.server.Svcs;
using Microsoft.AspNetCore.Http;

namespace housingsafety.server.SvcImpls
{
    class TokenHelper : ITokenHelper
    {
        private const string SecretKey = "d##wedfsSfcw3))e23rdDCSs*&%^fdfvxcf<w3qw3afdsfwe3!!!";

        public RespRet Valid(WebAPISign token, string jwt, HttpContext httpContext, long timestampSkewSec)
        {
            if (null == token)
            {
                return new RespRet(false, "token is empty");
            }

            if (string.IsNullOrEmpty(token.UserId))
            {
                return new RespRet(false, "UserId is empty");
            }

            if (string.IsNullOrEmpty(token.NonceStr))
            {
                return new RespRet(false, "NonceStr is empty");
            }

            if (string.IsNullOrEmpty(token.Sign))
            {
                return new RespRet(false, "Sign is empty");
            }

            var tk = new WebAPISecret(token, jwt, SecretKey, httpContext.Request.Path).ToSign();

            if (!string.Equals(tk.Sign, token.Sign))
            {
                return new RespRet(false, "Sign is not match");
            }

            var timestamp = DateTime.UtcNow.Ticks;
            var valid = new TimeSpan(timestamp - token.Timestamp).TotalSeconds < timestampSkewSec;
            return new RespRet(valid, valid ? "Ok" : "token is expired"); ;
        }

        public WebAPISign Make(string userId, string jwt, string uri)
        {
            return new WebAPISecret(userId, jwt, SecretKey, uri).ToSign();
        }
    }
}